import React,{useEffect,useState,useRef} from "react";



import { Text, View,StyleSheet,TouchableHighlight,TouchableOpacity, Linking,ScrollView, Alert,TextInput,Platform ,Image} from "react-native";
import * as S from "../Home/styles";
import { Avatar, HStack, Center, NativeBaseProvider ,ChevronRightIcon,useToast,ArrowBackIcon} from "native-base";
import {launchImageLibrary,launchCamera} from 'react-native-image-picker';
import { /*RFValue*/ } from "react-native-responsive-fontsize";
import Icon from 'react-native-vector-icons/Ionicons';
import { useGlobal } from '../../utils/GlobalContext';
import { getUeser,getCode,codeLogin } from "../../services/user";
import {
  CodeField,
  Cursor,
  useBlurOnFulfill,
  useClearByFocusCell,
} from 'react-native-confirmation-code-field';
import Spinner from 'react-native-loading-spinner-overlay';

const Loading = ({ loading, text }) => {
  // if (!loading) {
  //   return null;
  // }

  return (<Spinner
    visible={loading}
    textContent={text}
    cancelable={true}
    // customIndicator={ <Spinner2 size="lg" /> }
    // indicatorStyle={{margin:0,marginBottom:0}}
    overlayColor={'rgba(0, 0, 0, 0.5)'}
    textStyle={{ color: '#FFF',fontSize:16,fontFamily:'HarmonyOS Sans SC',fontWeight:'700' }}
    animation="fade"
  />
  );
};



const Title = ({navigation}:any)=>{
  return(
    <View style={styles.titleBox}>
      <TouchableOpacity
        style={styles.backBtn}
        onPress={() => {
          navigation.goBack()
        }}
      >
        <ArrowBackIcon size="5" />
      </TouchableOpacity>
    </View>
  )
}

const SMSCodeInput = ({route,navigation,setLoading}:any)=> {
  const { state, dispatch } = useGlobal();
  const [vcodeTxt,setvcodeTxt] = useState('')

  const onChangeText = (text)=>{
    setvcodeTxt(text)
    if(text.length>=6){
      // Alert.alert('登录')
      let obj = {
        phone:route.params.phone,
        code:text
      }
      setLoading(true)
      codeLogin(obj).then((res:any)=>{
        console.log(res)
        setLoading(false)
        dispatch({ type:'SET_TOKEN' , payload:res.data.token })
        dispatch({ type:'SET_USER' , payload:{} })
        getUserInfo()
        navigation.replace('Home')
      }).catch(()=>{
        setLoading(false)
      })
    }
  }

  const getUserInfo = ()=>{
    getUeser().then((res:any)=>{
      dispatch({ type:'SET_USER' , payload:res.data })
    })
  }


  return (
    <CodeField
      value={vcodeTxt}
      onChangeText={(text)=>{
        onChangeText(text)
        
      }}
      // 输入密码框的个数
      cellCount={6}
      rootStyle={styles.codeFiledRoot}
      keyboardType="number-pad"
      renderCell={({index, symbol, isFocused}) => (
        <View style={[styles.cell, (isFocused || symbol) && styles.focusCell]}>
            <Text
            key={index}
            style={styles.cellText}
          >
            {symbol || (isFocused ? <Cursor /> : null)}
          </Text>
        </View>
      )}
    />
  );
}


const Countdown =  ({route}:any)=>{

  const [count,setCount] = useState(60)


  const sendAgin = ()=>{

    let obj = {
      phone:route.params.phone
    }
    

    getCode(obj).then((res:any)=>{
      setCount(60)
      countDownTimer()
    })
  }
  

  const countDownTimer = async()=>{
    let seconds = 60;
    const countdown = () => {
      if (seconds > 0) {
        seconds--;
        setCount(seconds)
      } else {
        clearInterval(timer); // 清除定时器
        setCount(0)
      }
    };
    const timer = setInterval(countdown, 1000);
  }

  // const timer = setInterval(countdown, 1000);
  
  useEffect(() => {
    countDownTimer()
    return () => {

    };



  }, []);

 



  return (
    <View>
      {
        count 
        ? 
        <Text style={styles.countText}>{count}秒后可重新获取</Text> 
        : 
        <TouchableOpacity
        onPress={() => {
          sendAgin()
        }}
      >
        <Text style={styles.sendAginText}>重发短信验证码</Text>
      </TouchableOpacity>
        
      }
      
    </View>
  )

}







const Login = ({route,navigation}:any) => {
  const [ loading,setLoading ] = useState(false)
  return (
    <S.GrayContainer style={{backgroundColor:'#FFFFFF'}}>
      <NativeBaseProvider>
       <View style={styles.container}>
          <Title navigation={navigation}/>
          <ScrollView showsVerticalScrollIndicator={false}>
            <View style={styles.titleContent}>
              <Text style={styles.contentOne}>输入验证码</Text>
              <Text style={styles.contentTwo}>验证码发送至手机 {route.params.phone}</Text>
              <SMSCodeInput setLoading={setLoading} navigation={navigation} route={route}/>
              <Countdown route={route} />


            </View>
          </ScrollView>
          

         
       </View>
       <Loading loading={loading} text={'登录中...'}/>
      </NativeBaseProvider>
      
    </S.GrayContainer>
  );
};


export default Login;
const styles = StyleSheet.create({
  container:{
    height:"100%",
    width:'100%',
    // alignItems:'center',
    paddingHorizontal:24,
    
  },
  titleBox:{
    width:'100%',
    position:'relative',
    alignItems:'center',
    height:40,
    justifyContent:"center",
    marginBottom:26,
  },
  backBtn:{
    position:'absolute',
    left:0,
    backgroundColor:'#fff',
    width:40,
    height:40,
    display:'flex',
    alignItems:'center',
    justifyContent:'center',
    borderRadius:100,
    
    shadowColor: Platform.OS === 'android' ? '' : 'rgba(0, 0, 0, 0.08)', // 阴影颜色
    shadowOffset: { width: 0, height: 2 }, // 阴影偏移
    shadowOpacity: 1, // 阴影不透明度
    shadowRadius: 8, // 阴影半径
    elevation: 3, // 阴影深度
  },
  titleContent:{
    marginTop:10,
  },
  contentOne:{
    fontSize:28,
    fontWeight:'500',
    color:'#000000',
    fontFamily:'HarmonyOS_Sans_SC_Regular',
    marginBottom:8,
  },
  contentTwo:{
    fontSize:14,
    fontWeight:'400',
    fontFamily:'HarmonyOS_Sans_SC_Regular',
    color:'#8E8E93',
    // marginBottom:18,
  },
  codeFiledRoot: {
    marginTop: 80
  },
  // 里面每个密码小框的样式
  cell: {
    width: 50,
    height: 48,
    alignItems:'center',
    justifyContent:'center',
    borderBottomColor:'#ddd',
    borderBottomWidth:2,
    textAlign:'center',
    
  },
  cellText:{
    fontWeight:'700',
    fontSize: 32,
    color:"#2C2C2E",
    fontFamily:'HarmonyOS Sans SC',
  },
  // 当里面的每个密码小框被选中之后的样式
  focusCell: {
    borderBottomColor:'#4371B1',
  },
  countText:{
    marginTop:16,
    color:'#8E8E93',
    fontSize:14,
    fontFamily:'HarmonyOS Sans SC',
    textAlign:'center'
  },
  sendAginText:{
    marginTop:16,
    color:'#4371B1',
    fontSize:14,
    fontFamily:'HarmonyOS Sans SC',
    textAlign:'center'
  },
})
